package com.shsxt.service;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shsxt.controller.YunTongXun;
import com.shsxt.controller.base.BaseService;
import com.shsxt.dao.AuntDao;
import com.shsxt.dao.ControllDao;
import com.shsxt.dao.IUserinfoDao;
import com.shsxt.dao.WodeDao;
import com.shsxt.model.Activity;
import com.shsxt.model.BOrder;
import com.shsxt.model.COrder;
import com.shsxt.model.Coupon;
import com.shsxt.model.CustomerQuery;
import com.shsxt.model.DOrder;
import com.shsxt.model.JOrder;
import com.shsxt.model.KOrder;
import com.shsxt.model.Lunbo;
import com.shsxt.model.Notified;
import com.shsxt.model.ROrder;
import com.shsxt.model.ROrder2;
import com.shsxt.model.SOrder;
import com.shsxt.model.ServicePersonal;
import com.shsxt.model.SignIn;
import com.shsxt.model.UserInfo;
import com.shsxt.model.UserMessageQuery;
import com.shsxt.model.Userinfologin;
import com.shsxt.model.YOrder;
import com.shsxt.vo.CdkeyQuery;
import com.shsxt.vo.TongjiQuery;
import com.shsxt.vo.WithdrawQuery;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;



@Service
public class UserService extends BaseService<CustomerQuery>{

	@Autowired
	private IUserinfoDao dao;
	@Autowired
	private ControllService controllService;
	@Autowired
	private static WodeDao wodeDao;
	@Autowired
	private WodeService wodeService;
	@Autowired
	private ControllDao controllDao;
	@Autowired
	private AuntDao auntDao;
	/**
	 * 登录
	 */
	public Userinfologin islogin(String name,String pwd)
	{
		Userinfologin user=null;
		user=dao.islogin(name, pwd);
		return user;
	}
	/**
	 * 添加
	 * @param user
	 * @return
	 */
	public int add(Userinfologin user)
	{
		int row=0;
		dao.add(user);
		row=1;
		return row;
	}
	/**
	 * 查询所有的用户
	 */
	
	public List<Userinfologin> queryAll()
	{
		List<Userinfologin> list=dao.queryAll();
		
		return list;
	}
	/**
	 * 删除
	 */
	public int delete(int id)
	{
		int row=0;
		dao.delete(id);
		row=1;
		return row;
	}
	/**
	 * 根据id查询实体
	 */
	public Userinfologin queryById(int id)
	{
		Userinfologin user=null;
		user=dao.queryById(id);
		return user;
	}
	/**
	 * 修改用户
	 */
	public int update(int id,String name,String pwd)
	{
		int row=0;
		dao.update(id, name, pwd);
		row=1;
		return row;
	}
	
	 
	public Map<String, Object> testselectForPage(CustomerQuery saleChanceQuery,String state) throws ParseException {

		return super.testselectForPage(saleChanceQuery,state);
		
	}
	public Map<String, Object> testselectForPage(UserMessageQuery userMessageQuery,String state) throws ParseException {

		return super.testselectForPage(userMessageQuery,state);
		
	}
	public Map<String, Object> testselectForPage(WithdrawQuery withdrawQuery,String state) throws ParseException {

		return super.testselectForPage(withdrawQuery,state);
		
	}
	public Map<String, Object> add(ROrder rorder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.add(rorder);
		result.put("resultCode",1);
		return result;
	}
	//删除订单
	public Map<String, Object> deletelxc(String orderNumber) {
		dao.deletelxc(orderNumber);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
	//删除通知
	public Map<String, Object> deleteNotified(String id) {
		
		//如果删除的通知为未读,对应的用户通知数减一
		String[] ids=id.substring(1, id.length()-1).split(",");
		for(int i=0;i<ids.length;i++){
			Notified nf=auntDao.findNotifiedById(ids[i].substring(1, ids[i].length()-1));
			if(nf.getState().equals("未读")){
				//对应的阿姨未读通知数减一
				dao.updateNotifiedAunt2(nf.getPhoneNumber());
			}
		}
		dao.deleteNotified(id);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
	//删除兑换码
		public Map<String, Object> deleteCdkey(String cdkey) {
			dao.deleteCdkey(cdkey);	
			Map<String, Object> result=new HashMap<String, Object>();
			result.put("resultCode",1);
			return result;
		}
	//删除优惠券
	public Map<String, Object> deleteCoupon(String redeemCode) {
		dao.deleteCoupon(redeemCode);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
	//删除归属地
	public Map<String, Object> deleteLocation(String location) {
		dao.deleteLocation(location);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
//删除提现
	public Map<String, Object> deleteWithdraw(String id) {
		dao.deleteWithdraw(id);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
//删除统计
	public Map<String, Object> deleteTongji(String id) {
		dao.deleteTongji(id);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
//删除轮播
	public Map<String, Object> deleteLunbo(String lunbo,HttpSession session) throws IOException  {
		String[] ids=lunbo.substring(1, lunbo.length()-1).split(",");
			//删除服务器的轮播图
		for(int i=0;i<ids.length;i++){
			String after=ids[i].substring(1, ids[i].length()-1).split("images/")[1];
			String begin = session.getServletContext().getRealPath("images")+File.separator;// 储存地址+文件名 
			String path=(begin+after);
			File f=new File(path);
			FileOutputStream out=new FileOutputStream(f);
			out.close();
			f.delete();
		
		}
			
	        
	        dao.deleteLunbo(lunbo);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}	
//删除轮播
	public Map<String, Object> deleteActivity(String id,HttpSession session) throws IOException {
		//删除服务器的轮播图
		String[] ids=id.substring(1, id.length()-1).split(",");
		for(int i=0;i<ids.length;i++){
			Activity activity=controllDao.findActivityByid(ids[i].substring(1, ids[i].length()-1));
			String after=activity.getFirst_PrictureAddress().split("images/")[1];
			String after2=activity.getDetailPicture().split("images/")[1];

			String begin = session.getServletContext().getRealPath("images")+File.separator;// 储存地址+文件名 
			String path=begin+after;
			String path2=begin+after2;
			 File targetFile = new File(path);
			 File targetFile2 = new File(path2);
			 FileOutputStream out=new FileOutputStream(targetFile);
			out.close();
			 FileOutputStream out2=new FileOutputStream(targetFile2);
			out2.close();
		        if(targetFile.exists()){
		        	targetFile.delete();
		        }
		        if(targetFile2.exists()){
		        	targetFile2.delete();
		        }
		}
		
			dao.deleteActivity(id);	

		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}	
//修改上班状态
	public Map<String, Object> updateStage(String phoneNumber) {
		dao.updateStage(phoneNumber);	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
//修改转账状态
	public Map<String, Object> openWithdraw(String id) throws APIConnectionException, APIRequestException {
		//1把原来为转账的阿姨 余额扣掉   2生成统计记录3发送通知
		Map<String,Object> param=new HashMap<String,Object>();
		String[] ids=(id.substring(1, id.length()-1)).split(",");
		for(int i=0;i<ids.length;i++){
			WithdrawQuery tj=controllDao.findWithdrawByid(ids[i].substring(1, ids[i].length()-1));
			if(tj.getState().equals("未转账")){
				ServicePersonal sp=auntDao.findAuntByServicePersonal(tj.getAunt());
				param.put("balance", tj.getCount().substring(1,  tj.getCount().length()));
				param.put("phoneNumber", sp.getPhoneNumber());
				/*auntDao.updateBalanceBywithdraw(param);*/
				 param.put("type", "阿姨提现");
      			param.put("message", "阿姨:"+sp.getPhoneNumber());
      			param.put("count", "-"+param.get("balance"));
      			controllDao.createTongji(param);
      			//发送通知
      			Notified notified=new Notified();
      			notified.setPhoneNumber(tj.getAunt());
				notified.setType("阿姨");
				notified.setDetailType("提现通知");
				notified.setNotifiedContent("您申请的提现现已转账成功!"+tj.getCount());
				notified.setNotifiedTime(new Date());
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedAunt(notified.getPhoneNumber());
				ControllService.pushOne("587fc17e9c0cc048c2a3e10a","b2588d7dcaa473f3975c86fc",notified.getNotifiedContent(),notified.getPhoneNumber());
		
			}
		}
		//修改转账明细为已转账
		dao.openWithdraw(id);
	
		Map<String, Object> result=new HashMap<String, Object>();
		result.put("resultCode",1);
		return result;
	}
	public Map<String, Object> rupdatelxc(ROrder rorder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateR(rorder);
		result.put("resultCode",1);
		return result;
	}
	public Map<String, Object> supdatelxc(SOrder sorder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateS(sorder);
		result.put("resultCode",1);
		return result;
	}public Map<String, Object> kupdatelxc(KOrder korder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateK(korder);
		result.put("resultCode",1);
		return result;
	}public Map<String, Object> jupdatelxc(JOrder jorder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateJ(jorder);
		result.put("resultCode",1);
		return result;
	}public Map<String, Object> dupdatelxc(DOrder dorder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateD(dorder);
		result.put("resultCode",1);
		return result;
	}public Map<String, Object> cupdatelxc(COrder corder) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateC(corder);
		result.put("resultCode",1);
		return result;
	}
	public Map<String, Object> zupdatelxc(ROrder2 rorder) {
		String[] times=rorder.getOrderTime().split(";");
		String orderTime="";
		String day="";
		String slot="";
		for(String str:times){
			day=day+str.split(",")[0]+",";
			slot=slot+str.split(",")[1]+",";
		}
		orderTime=day.substring(0,day.length()-1)+";"+slot.substring(0,slot.length()-1);
		rorder.setOrderTime(orderTime+";"+rorder.getSupportType()+";"+rorder.getRobListType());

		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateZ(rorder);
		result.put("resultCode",1);
		return result;
	}
	public Map<String, Object> yupdatelxc(YOrder yorder) {
	Map<String, Object> result=new HashMap<String, Object>();
	dao.updateY(yorder);
	result.put("resultCode",1);
	return result;
	}
	
	public Map<String, Object> bupdatelxc(BOrder border) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateB(border);
		result.put("resultCode",1);
		return result;
		}

	@SuppressWarnings("static-access")
	public Map<String, Object> user_message_add(UserInfo user) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateUserMessage(user);
		exchangeCreditsHouTai(user.getPhoneNumber());
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> aunt_message_add(ServicePersonal user) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateAuntMessage(user);
		result.put("resultCode",1);
		return result;
		}
	
	public Map<String, Object> withadd(WithdrawQuery user) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateWithMessage(user);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> tongjiadd(TongjiQuery user) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateTongjiMessage(user);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> cdkeyadd(CdkeyQuery cdkey) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateCdkeyMessage(cdkey);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> couponadd(Coupon coupon) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.updateCouponMessage(coupon);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> cdkeySendadd(CdkeyQuery cdkey) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.addCdkeySendMessage(cdkey);
		if(cdkey.getUser()!=null||!cdkey.getUser().equals("")){
			String[] dat={cdkey.getCdkey()+""};/*180865*/
			new YunTongXun().register(cdkey.getUser(),"86615",dat);
		}
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> couponSendadd(Coupon coupon) {
		Map<String, Object> result=new HashMap<String, Object>();
		List<UserInfo> users=wodeDao.findUsers();
		for(UserInfo user:users){
			coupon.setPhoneNumber(user.getPhoneNumber());
			coupon.setRedeemCode(UUID.randomUUID().toString().substring(0, 8));
			dao.addCouponSendMessage(coupon);
		}
		result.put("resultCode",1);
		return result;
		}
	//添加阿姨
	public Map<String, Object> auntAdd(ServicePersonal user) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.addAunt(user);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> notifiedadd(Notified notified) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.addNotifiedMessage(notified);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> activityadd(Activity activity) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.addActivityMessage(activity);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> lunboadd(Lunbo lunbo) {
		Map<String, Object> result=new HashMap<String, Object>();
		dao.addLunboMessage(lunbo);
		result.put("resultCode",1);
		return result;
		}
	public Map<String, Object> createNotifiedadd(Notified notified) throws APIConnectionException, APIRequestException {
		Map<String, Object> result=new HashMap<String, Object>();
		/*1查询所有的用户
		 *2为所有用户创建未读通知 
		 *3修改用户信息 notified字段+1 
		 *4发送用户通知 
		 */
		if(notified.getType().equals("用户")){
			List<UserInfo> users=dao.findUsers();
			for(UserInfo user:users){
				notified.setPhoneNumber(user.getPhoneNumber());
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedUser(user.getPhoneNumber());
				result.put("resultCode",1);
			}
			ControllService.push("8f6965a441a0aa10011c7063","1dd0e3924e7394137bc20d57",notified.getNotifiedContent());
		}else if(notified.getType().equals("阿姨")){
			List<ServicePersonal> aunts=dao.findAunts();
			for(ServicePersonal aunt:aunts){
				notified.setPhoneNumber(aunt.getPhoneNumber());
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedAunt(aunt.getPhoneNumber());
				result.put("resultCode",1);
			}
			ControllService.push("587fc17e9c0cc048c2a3e10a","b2588d7dcaa473f3975c86fc",notified.getNotifiedContent());

		}else{
			UserInfo user=wodeDao.findUserByPhone(notified.getType());
			ServicePersonal sp= auntDao.findAuntByServicePersonal(notified.getType());
			if(user!=null&&sp==null){
			notified.setPhoneNumber(notified.getType());
			notified.setType("用户");
			dao.createNotifiedMessage(notified);
			dao.updateNotifiedUser(notified.getPhoneNumber());
			result.put("resultCode",1);
			ControllService.pushOne("8f6965a441a0aa10011c7063","1dd0e3924e7394137bc20d57",notified.getNotifiedContent(),notified.getPhoneNumber());
			}else if(user==null&&sp!=null){
				notified.setPhoneNumber(notified.getType());
				notified.setType("阿姨");
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedAunt(notified.getPhoneNumber());
				result.put("resultCode",1);
				ControllService.pushOne("587fc17e9c0cc048c2a3e10a","b2588d7dcaa473f3975c86fc",notified.getNotifiedContent(),notified.getPhoneNumber());
			}else if(user!=null&&sp!=null){
				/*notified.setPhoneNumber(notified.getType());
				notified.setType("用户");
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedUser(notified.getPhoneNumber());
				result.put("resultCode",1);
				System.err.println(notified.getNotifiedContent()+"-=="+notified.getPhoneNumber());
				ControllService.pushOne("8f6965a441a0aa10011c7063","1dd0e3924e7394137bc20d57",notified.getNotifiedContent(),notified.getPhoneNumber());
				
				notified.setType("阿姨");
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedAunt(notified.getPhoneNumber());
				ControllService.pushOne("587fc17e9c0cc048c2a3e10a","b2588d7dcaa473f3975c86fc",notified.getNotifiedContent(),notified.getPhoneNumber());
*/
				notified.setPhoneNumber(notified.getType());
				notified.setType("阿姨");
				dao.createNotifiedMessage(notified);
				dao.updateNotifiedAunt(notified.getPhoneNumber());
				result.put("resultCode",1);
				ControllService.pushOne("587fc17e9c0cc048c2a3e10a","b2588d7dcaa473f3975c86fc",notified.getNotifiedContent(),notified.getPhoneNumber());
			}

		}
		
		return result;
		}
	public static void deleteFile(String path) throws IOException {
		File f = new File(path);
		DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
		dos.close();
		 if (f.exists()) {
		                    if (!f.delete()) {
		                        System.out.println("请关闭使用该文件的所有进程或者流！！");
		                    } else {
		                        System.out.println(f.getName()+" 成功被删除！");
		                    }
		                }
    }
	//签到表里的积分提到用户表里面 相反
	public  void exchangeCreditsHouTai(String phoneNumber) {
		System.err.println("phoneNumber"+phoneNumber);
	Map<String,Object> param=new HashMap<String,Object>();
		SignIn sign=dao.findSignByPhone(phoneNumber);
		if(sign==null){
			dao.createSign(phoneNumber);
		}
		UserInfo user=dao.findUserByPhone(phoneNumber);
		param.put("credits",user.getPoints());
		param.put("phoneNumber", phoneNumber);
		dao.updateCredits(param);
	}
	
}
